package com.demo.mystudy.ui.socketserver

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.demo.mystudy.R
import com.demo.mystudy.databinding.DialogSocketBinding
import com.jetinno.simple.SimpleDialogFragment
import com.jetinno.simple.utils.FragmentsUtil
import com.jetinno.simple.utils.IpUtil
import kotlinx.coroutines.launch
import timber.log.Timber


/**
 * Created by zhangyuncai on 2025/4/25.
 * 描述：
 */
class SocketDF : SimpleDialogFragment() {
    lateinit var mDB: DialogSocketBinding
    private val mAdapter by lazy { SocketAdapter(WebSocketServerManager.mDatas) }
    override fun useDatabing(inflater: LayoutInflater, container: ViewGroup?): View? {
        mDB = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        return mDB.root
    }

    override fun getLayoutId(): Int {
        return R.layout.dialog_socket
    }

    override fun initView() {
        mDB.rvSocketReceivemsg.run {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
        }

        val ip = IpUtil.getLocalIpAddress(mContext)
        mDB.tvSocketIp.text = "${ip}:9527"
        Timber.i("ip:${ip}")

        mDB.cbSocketStatus.isChecked = WebSocketServerManager.isOpened
    }

    override fun initEvent() {
        WebSocketServerManager.callback = object : SocketServerCallback {
            override fun addData(msg: String) {
                lifecycleScope.launch {
                    mAdapter.notifyDataSetChanged()
                }
            }

            override fun onSocketStatusChanged(isOpened: Boolean) {
                lifecycleScope.launch {
                    mDB.cbSocketStatus.isChecked = WebSocketServerManager.isOpened
                }
            }

        }
        mDB.headbar.setBackClickListener {
            finish()
        }
        mDB.btSocketOpen.setOnClickListener {
            WebSocketServerManager.openSocket()
        }

        mDB.btSocketClose.setOnClickListener {
            WebSocketServerManager.closeSocket()
        }

    }

    override fun initData() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        WebSocketServerManager.callback = null
    }

    companion object {
        fun showSocketDF(fragmentManager: FragmentManager, context: Context) {
            FragmentsUtil.showDialog(fragmentManager, context, SocketDF::class.java)
        }
    }
}